<template>
  <div class="handle-data-container">
    <el-dialog v-model="dialog" :title="dialogTitle" top="50px" :before-close="cancelForm" :close-on-click-modal="false">
      <div class="demo-drawer__content">
        <el-form class="handle-form-container" :model="form" ref="handleForm" v-if="HandlerItemData && HandlerItemData.length">
          <div v-for="handlerItem in HandlerItemData" :key="handlerItem.key">
            <el-form-item v-if="!inputShowAdd(handlerItem.key)" :key="handlerItem.key" :label="handlerItem.label" :label-width="120" :prop="handlerItem.key">
              <el-input v-if="handlerItem.category === 'input'" v-model="form[handlerItem.key]" :type="handlerItem.type"
                :disabled="handlerItem.updateDisabled && updateDisabled">
                <template v-if="handlerItem.key === 'bidfloor' || handlerItem.key === 'budget'" #append>元</template>
              </el-input>
              <el-select v-else-if="handlerItem.category === 'select'" v-model="form[handlerItem.key]"
                placeholder="Select"
                :disabled="handlerItem.key === 'status' && props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD">
                <el-option v-for="optionItem in handlerItem.options" :key="optionItem.value" :label="optionItem.label"
                  :value="optionItem.value" />
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div class="footer-container">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" @click="onClick">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
  
<script setup lang='ts'>
/**
 * 新增的时候 pkg 和 md5需要格外注意，后端有校验
 * 
 http://tf.jinshanju.com/manage/add?
 name=helloworld&pkg=com.ss.android.ugc.aweme.lite&md5=b8af36e762cf98511054e2c678dc2018
 &url=12123&vnm=12.1.1&vcd=120101&cpuModel=&keywords=&bidfloor=1200
 &budget=1200&downloadnum=12&channel=hemu_dsp&mlink=&tagid=&size=12
 * 
 */
import { reactive, ref, watch, defineProps, computed } from 'vue';
// import { ElMessage } from 'element-plus'
import { HandlerItemData as OriginHandlerItemData, HANDLE_TYPE_ENUM } from '../../../types/home/constData';
import type { IHandlerItemData, IListItemData } from '../../../types/home/type'
import { multiplicationHundred, divisionHundred } from '@/utils/index'
import { reqManagelistAdd, reqManagelistUpdate, reqManagelistItem } from '@/api/home/index.ts'
// 去掉 detailList(广告位、cpm出价、关键词) 其他都展示
const HandlerItemData = JSON.parse(JSON.stringify(OriginHandlerItemData))
HandlerItemData.splice(10, 1);
const emit = defineEmits(['onHandlerCompleted'])
const props = defineProps<{
  originData: any,
  handleType: string
}>()
const handleForm = ref()
const dialogTitle = ref<string>('新增')
const dialog = ref<boolean>(false)
const updateDisabled = ref<boolean>(false)
const formNoneVal: IListItemData = {
  name: '',
  pkg: '',
  md5: '',
  url: '',
  vnm: '',
  vcd: '',
  cpuModel: '',
  keywords: '',
  bidfloor: null,
  budget: null,
  downloadnum: null,
  channel: '',
  mlink: '',
  tagid: '',
  size: '',
  rtaurl: '',
  customer: '',
}
let form = reactive<IListItemData>(formNoneVal)
const updateOriginStatus = ref<number | null>(null)

// 新增的时候 appid 和 status 不展示
const inputShowAdd = computed(()=> (key: string) => {
  if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
    return key === 'appid' || key === 'status'
  }
  return false
})
const cancelForm = () => {
  handleForm.value.resetFields()
  form = reactive<IListItemData>(formNoneVal)
  updateDisabled.value = false
  handleDialog(false)
}
const onClick = () => {
  const isValiate = valiateForm()
  if (!isValiate) return
  onSubmit()
}

const onSubmit = () => {
  let requestFunc: Function | null = null
  if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
    requestFunc = reqManagelistAdd
  } else {
    requestFunc = reqManagelistUpdate
  }
  const targetForm = {
    ...form,
    bidfloor: multiplicationHundred(form.bidfloor!),
    budget: multiplicationHundred(form.budget!),
    id: form.appid,
    cpumodel: form.cpuModel,
  }
  targetForm.msg && delete targetForm.msg
  if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
    targetForm.status && delete targetForm.status
    targetForm.appid && delete targetForm.appid
    targetForm.id && delete targetForm.id
  } else {
    targetForm.pkg && delete targetForm.pkg
    targetForm.vnm && delete targetForm.vnm
    targetForm.vcd && delete targetForm.vcd
    targetForm.customer && delete targetForm.customer
  }
  if (requestFunc == null) return
  requestFunc(targetForm).then((res: any) => {
    const { code, data, msg } = res
    if (code === 0) {
      console.log(data)
      ElMessage({
        type: 'success',
        message: `${dialogTitle.value}成功`
      })
      emit('onHandlerCompleted')
      cancelForm()
    } else {
      ElMessage({
        type: 'warning',
        message: msg
      })
    }
  })
}


const valiateForm = () => {
  for (let index = 0; index < HandlerItemData.length; index++) {
    const item: IHandlerItemData = HandlerItemData[index]
    const keyMapVal: any = `${form[item.key as string]}`
    if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
      if (!!item.require && !keyMapVal) {
        const message = `${item.label}为必填项`
        ElMessage({
          type: 'warning',
          message
        })
        return false
      }
    } else {
      if (!!item.require && !item.updateDisabled && !keyMapVal) {
        const message = `${item.label}为必填项`
        ElMessage({
          type: 'warning',
          message
        })
        return false
      }
    }
  }
  // 更新时，任何状态都可以改成下架=-3，但只有-3可以改成上架=0
  if (props.handleType === HANDLE_TYPE_ENUM.TYPE_UPDATE && form.status === 0 && updateOriginStatus.value !== -3) {
    ElMessage({
      type: 'warning',
      message: '只有下架状态才能修改为上架'
    })
    return false
  }
  return true
}
watch(dialog, (newVal) => {
  setTimeout(() => {
    if (!!newVal) {
      if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
        dialogTitle.value = '新增'
      } else {
        dialogTitle.value = '更新'
        getManagelistItem(props.originData.appid)
      }
    }
  }, 0)
})
const resetFormValue = (data: any) => {
  form = Object.assign(form, data)
  // 更新时，任何状态都可以改成下架=-3，但只有-3可以改成上架=0
  updateOriginStatus.value = form.status!
  updateDisabled.value = true
}
const getManagelistItem = (appid: string | undefined) => {
  reqManagelistItem({ appid }).then((res: any) => {
    const { code, data, msg } = res
    if (code === 0) {
      if (data.bidfloor != null && data.bidfloor != undefined) {
        data.bidfloor = divisionHundred(Number(data.bidfloor))
      }
      if (data.budget != null && data.budget != undefined) {
        data.budget = divisionHundred(Number(data.budget))
      }
      resetFormValue(data)
    } else {
      ElMessage({
        type: 'warning',
        message: msg
      })
    }
  })
}
const handleDialog = (val: boolean) => {
  dialog.value = val
}

defineExpose({
  handleDialog
})
</script>
  
<style scope lang="scss">
.demo-drawer__content{
  .handle-form-container{
    height: 700px;
    overflow: auto;
    padding-right: 15px;
  }
}
.footer-container {
  margin-top: 30px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>